package com.example.bm.system.controller;

import cn.hutool.core.convert.Convert;
import com.example.bm.common.controller.BaseController;
import com.example.bm.system.service.RegionService;
import com.example.common.domain.Layui;
import com.example.common.exception.ServiceException;
import com.example.dao.model.TRegion;
import com.github.pagehelper.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;


/**
 * Controller
 *
 * @author majian
 * @date 2019-11-11
 */
@Slf4j
@Controller()
@RequestMapping("/sys/region")
public class RegionController extends BaseController {

    @Autowired
    private RegionService regionService;


    /**
     * 首页
     *
     * @param modelAndView
     * @return
     */
    @GetMapping(value = "/index")
    public ModelAndView index(ModelAndView modelAndView) {
        modelAndView.setViewName("views/tRegion/tRegionList");
        return modelAndView;
    }

    /**
     * 明细
     *
     * @param params
     * @return
     */
    @PostMapping("/list")
    @ResponseBody
    public Layui<List<TRegion>> list(@RequestParam Map<String, String> params, HttpServletRequest request) {
        log.info("TRegion明细 list={}", params);
        try {
            int pageNum = Convert.toInt(params.get("page"));
            int pageSize = Convert.toInt(params.get("limit"));
            Page<TRegion> list = regionService.getPageList(params, pageNum, pageSize);
            return Layui.success(list.getResult(), list.getTotal());
        } catch (ServiceException e) {
            log.info(e.getMessage());
            return Layui.error(e.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Layui.error();
    }

    /**
     * 查询所有
     *
     * @param params
     * @return
     */
    @RequestMapping("/listAll")
    @ResponseBody
    public Layui<List<TRegion>> listAll(@RequestParam Map<String, String> params, HttpServletRequest request) {
        log.info("查询所有 queryList={}", params);
        try {
            List<TRegion> list = regionService.getBaseMapper().selectList(null);
            return Layui.success(list, (long) list.size());
        } catch (ServiceException e) {
            log.info(e.getMessage());
            return Layui.error(e.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Layui.error();
    }

    /**
     * 新增
     *
     * @param modelAndView
     * @return
     */
    @GetMapping(value = "/addPage")
    public ModelAndView addPage(ModelAndView modelAndView) {
        modelAndView.setViewName("views/tRegion/tRegionAdd");
        return modelAndView;
    }

}
